import {LOGIN_WELOCOME_TEXT, SITE_COMPANY_NAME, SYSTEM_NAME} from "@/constants";
import {Button, Divider, Form, Input, message} from 'antd';
import './index.less';
import {useModel, history} from '@umijs/max';
import {passwordLogin} from '@/services/login/LoginService';
import {setAuthInfo} from '@/utils/auth';
import {flushSync} from 'react-dom';
import React from 'react';
import * as API from "@/services";

interface LoginProps {
}

const Login: React.FC<LoginProps> = (props) => {
  const [form] = Form.useForm();

  const {initialState, refresh, setInitialState} = useModel('@@initialState');

  const handleSubmit = async (values: API.PasswordLoginReq) => {
    const submitValues = {...values, tenantId: '1'};
    // 登录
    try {
      const resp = await passwordLogin({...submitValues}, {skipErrorHandler: true});
      if (resp.flag) {
        setAuthInfo(resp.data);
        message.success('登录成功！');
        const loggedInfo = await initialState?.fetchLoggedInfo?.();
        if (loggedInfo) {
          //同步等待 react 18 only, 避免异步时 app.tsx的layout中拿不到initialState的问题
          flushSync(() => {
            setInitialState((s) => ({
              ...s,
              ...loggedInfo,
            }));
          });
        }
        const urlParams = new URL(window.location.href).searchParams;
        //尝试获取url中的redirect参数(地址), 如果有就重定向到这个地址,否则就去首页"/"
        const redirectTarget = urlParams.get('redirect');
        history.push(redirectTarget || '/');
        return;
      }
    } catch (e: any) {
      if ([400058, 400059].includes(e.response?.data?.bizcode)) {
        ///login/anoo-modify-pwd
        history.push(`/login/anoo-modify-pwd?cause=${e.response?.data?.bizcode}`, {
          ...values
        });
      } else if (e.response?.data?.msg) {
        message.error(e.response?.data?.msg)
      }
    }
  };

  return (
    <div className={'login-container'}>
      <div className={'login-container-inner'}>
        <div className={'login-container-header'}>
          {
            LOGIN_WELOCOME_TEXT && <p>{LOGIN_WELOCOME_TEXT}</p>
          }
          <h2>{SITE_COMPANY_NAME}</h2>
          <h5>{SYSTEM_NAME}</h5>
          <Divider/>
        </div>
        <Form
          labelCol={{span: 24}}
          wrapperCol={{span: 24}}
          form={form}
          layout={'vertical'}
          name="login-form"
          autoComplete="off"
          onFinish={async (values) => {
            await handleSubmit(values as API.PasswordLoginReq);
          }}
        >
          <Form.Item label="用户名" name="loginName" rules={[{required: true, message: '请输入您的登录用户名!'}]}>
            <Input placeholder={'请输入您的登录用户名'}/>
          </Form.Item>

          <Form.Item label="密码" name="password" rules={[{required: true, message: '请输入您的登录密码!'}]}>
            <Input.Password placeholder={'请输入您的登录密码'}/>
          </Form.Item>

          <Form.Item>
            <Button className={'login-submit-btn'} type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
